package com.example.administrator.myapplication.flexibility;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.myapplication.BmobApplication;
import com.example.administrator.myapplication.HomeActivity;
import com.example.administrator.myapplication.MainActivity;
import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.evaluate.TestAssess;
import com.example.administrator.myapplication.tools.CameraUse;
import com.example.administrator.myapplication.tools.PictureFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import static android.app.Activity.RESULT_OK;


public class flexibility_main_Fragment extends Fragment {
    private Toolbar toolbar;
    private LinearLayout layout_choose;
    private TextView tv_picture;
    private TextView tv_choose_photo;
    private ImageView iv_soft_choose;
    private ImageView iv_soft_camera;
    private ImageView iv_soft_album;
    private BmobApplication soft_apps;
    private Button bt_soft_submit;
    private Uri uri;
    private File file;
    private Dialog dialog;
    private Bitmap bitmap;
    private static int TAKEPHOTO = 1;
    private static int CHOOSEPHOTO = 2;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_flexibility_main_, container, false);

        iv_soft_choose = (ImageView) view.findViewById(R.id.iv_soft_choose);
        bt_soft_submit= (Button) view.findViewById(R.id.bt_soft_submit);
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_flexibility);
        soft_apps= (BmobApplication) getActivity().getApplication();
        iv_soft_camera = (ImageView) view.findViewById(R.id.iv_soft_camera);
        iv_soft_album = (ImageView) view.findViewById(R.id.iv_soft_album);

        toolbar.setNavigationIcon(R.mipmap.custom_back);
        toolbar.setTitle("柔韧性适能");
        toolbar.setTitleMarginStart(100);
        toolbar.setTitleTextColor(Color.parseColor("#ffffff"));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(getActivity(), HomeActivity.class);
                getActivity().finish();
                startActivity(intent);
            }
        });

        bt_soft_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                soft_apps.setFlag(3);
                soft_apps.setIntentflag(0);
                float angle = (float) (Math.random() * 100);  //角度
                int softscore;
                if (soft_apps.is_man()){
                    if (angle >= 68){
                        softscore = 0;
                    }
                    else if (angle > 32 && angle < 68){
                        softscore = (int)(2.7778 * (68 - angle));
                    }
                    else
                        softscore = 100;
                }
                else {
                    if (angle >= 61){
                        softscore = 0;
                    }
                    else if (angle > 26 && angle < 61){
                        softscore = (int)(2.8571 * (61 - angle));
                    }
                    else
                        softscore = 100;
                }
                soft_apps.setSoft_result(String.valueOf(softscore));
                Intent intent =new Intent(getActivity(),TestAssess.class);
                getActivity().finish();
                startActivity(intent);

            }
        });

        layout_choose = (LinearLayout) view.findViewById(R.id.layout_flexibility_choose);
        /*layout_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                //创建一个view对象并显示出来
                final View softview = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_soft_choose, null);
                dialog = builder.setView(softview).show();
                tv_picture = (TextView) softview.findViewById(R.id.tv_soft_picture);
                tv_choose_photo = (TextView) softview.findViewById(R.id.tv_soft_choose_photo);
                tv_picture.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //调用相机的摄像头
                        //把照片存在softpicture.jpg 这个文件上
                        file = new File(getActivity().getFilesDir(), "takephoto.jpg");
                        if (!file.exists()) {
                            try {
                                file.createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (Build.VERSION.SDK_INT >= 24) {
                            uri = FileProvider.getUriForFile(getActivity(), "com.example.administrator.myapplication.fileprovider", file);
                        } else {
                            uri = Uri.fromFile(file);
                        }
                        CameraUse cameraUse = new CameraUse();
                        Intent intent = cameraUse.UseCamera(uri);
                        //注意这个arg1是代表requestcode
                        startActivityForResult(intent, TAKEPHOTO);
                        dialog.dismiss();


                    }
                });
                tv_choose_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //调用相册选择图片
                        Intent albumintent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(albumintent, CHOOSEPHOTO);
                        dialog.dismiss();
                    }
                });

            }
        });*/
        iv_soft_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用相机的摄像头
                //把照片存在softpicture.jpg 这个文件上
                file = new File(getActivity().getFilesDir(), "takephoto.jpg");
                if (!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (Build.VERSION.SDK_INT >= 24) {
                    uri = FileProvider.getUriForFile(getActivity(), "com.example.administrator.myapplication.fileprovider", file);
                } else {
                    uri = Uri.fromFile(file);
                }
                CameraUse cameraUse = new CameraUse();
                Intent intent = cameraUse.UseCamera(uri);
                //注意这个arg1是代表requestcode
                startActivityForResult(intent, TAKEPHOTO);
//                dialog.dismiss();
            }
        });
        iv_soft_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用相册选择图片
                Intent albumintent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(albumintent, CHOOSEPHOTO);
//                dialog.dismiss();
            }
        });


        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                //resultCode 拍照成功返回 RESULT_OK
                if(resultCode == RESULT_OK) {
                    if (data != null) {
                        if (data.hasExtra("data")) {
                            Bitmap bitmap = data.getParcelableExtra("data");
                            iv_soft_choose.setImageBitmap(bitmap);//imageView即为当前页面需要展示照片的控件，可替换
                        }
                    } else {
                        if (Build.VERSION.SDK_INT >= 24) {
                            bitmap = null;
                            try {
                                bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri));
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

                        } else {
                            bitmap = BitmapFactory.decodeFile(uri.getPath());
                        }
                        Drawable drawable =new BitmapDrawable(bitmap);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            iv_soft_choose.setBackground(drawable);
                        }else{
                            iv_soft_choose.setImageDrawable(drawable);
                        }
                    }
                }
                break;
            case 2:
                if( resultCode==RESULT_OK ){
                    Uri SelectImageUri=data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getActivity().getContentResolver().query(SelectImageUri, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    Bitmap bm =PictureFactory.shrinkPic(picturePath,getActivity());
                    Drawable drawable=new BitmapDrawable(bm);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        iv_soft_choose.setBackground(drawable);
                    }else {
                        iv_soft_choose.setImageDrawable(drawable);
                    }
                }
                break;
        }
    }
//    //这个方法用来缩放图片功能
//    public Bitmap decodePic (String path){
//        BitmapFactory.Options options=new BitmapFactory.Options();
//        //只获取宽高，不获取像素
//        options.inJustDecodeBounds=true;
//        Bitmap bitmap =BitmapFactory.decodeFile(path,options);
//        //获取图片的宽高
//        float density=getResources().getDisplayMetrics().density;
//        // 通过getIntrinsic 获得ImageView中Image的真实宽高，
//        int picwd= (int) (iv_soft_choose.getDrawable().getBounds().width()/density);
//        int picht= (int) (iv_soft_choose.getDrawable().getBounds().height()/density);
//
//        int mapwd =options.outWidth;
//        int mapht =options.outHeight;
//        //缩放比例默认为1
//        int scale =1;
//        int scaleWidth =mapwd/picwd;
//        int scaleHeight =mapht/picht;
//        //哪一个比例大就用哪一个
//        if(scaleWidth>=scaleHeight){
//            scale =scaleWidth;
//        }else{
//            scale =scaleHeight;
//        }
//        //设置缩放比例
//        options.inSampleSize=scale;
//        //设置获取像素信息
//        options.inJustDecodeBounds=false;
//        Bitmap bm =BitmapFactory.decodeFile(path,options);
//        return bm;
//
//    }
}
